﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Linq;
using System.Text;
using Maverick.Domain.Abstract;
using Maverick.Domain.Entities;
using MWPF.Utilities.DataCleansing;

namespace Maverick.Domain.Concrete
{
    public class SqlMessagesRepository : IMessagesRepository
    {
        private Table<Message> messagesTable;
        private Table<Category> categoriesTable;
        
        public SqlMessagesRepository (string connectionString)
        {
            DataContext dc = new DataContext(connectionString);
            messagesTable = dc.GetTable<Message>();
            categoriesTable = dc.GetTable<Category>();
        }

        public IQueryable<Category> Categories
        {
            get
            {
                return categoriesTable;
            }
        }

        public IQueryable<Message> Messages
        {
            get
            {
                return messagesTable;
            }
        }

        public void SaveMessage(Message message)
        {                        
            if (message.MessageID == 0)
            {
                messagesTable.InsertOnSubmit(message);
            }
            else if (messagesTable.GetOriginalEntityState(message) == null)
            {
                messagesTable.Attach(message);
                messagesTable.Context.Refresh(RefreshMode.KeepCurrentValues, message);
            }

            messagesTable.Context.SubmitChanges();
        }

        public void DeleteMessage (Message message)
        {
            messagesTable.DeleteOnSubmit(message);
            messagesTable.Context.SubmitChanges();
        }
    }
}
